<?php
  include('../includes.php');
  $membership = New Membership();
  $membership->confirm_member(); 

  $action  = $_POST['action'];
  $datum   = explode('/', $_POST['datum']);
  $dag     = $datum[0];
  $week    = $datum[1];
  $jaar    = $datum[2];
  $tijd    = $_POST['tijd'];
  $les_id  = $_POST['les'];
  $user_id = $_POST['user'];

  if ($action === "aanmelden")
    mysql_query('INSERT INTO '.DB_DEELNEMER.' (les_ID, user_ID) VALUES ("'.$les_id.'", "'.$user_id.'")');
  else if ($action == "afmelden")
  {
    $current_day  = date('j');
    $current_week = Website::week_format(date('W'));
    $current_time = date('H:i');

    /* Haal het ID op van diegene die als eerst gereserveerd heeft */
    $query = mysql_query('SELECT user_ID, MIN(counter) FROM '.DB_RESERVERING.' WHERE les_ID="'.$les_id.'" GROUP BY les_ID');
    $row = mysql_fetch_assoc($query);

    $counter    = $row['MIN(counter)'];
    $reserve_id = $row['user_ID']; 

    mysql_query('INSERT INTO '.DB_AFMELDING.' (les_ID, user_ID, afmeld_dag, week, afmeld_tijd) VALUES ("'.$les_id.'", "'.$user_id.'", "'.$current_day.'", "'.$current_week.'", "'.$current_time.'")');
    mysql_query('DELETE FROM '.DB_DEELNEMER.' WHERE les_ID="'.$les_id.'" AND user_ID="'.$user_id.'"');

    if ($counter)
      if (mysql_query('INSERT INTO '.DB_DEELNEMER.' (les_ID, user_ID) VALUES ("'.$les_id.'", "'.$reserve_id.'")'))
        mysql_query('DELETE FROM '.DB_RESERVERING.' WHERE les_ID="'.$les_id.'" AND user_ID="'.$reserve_id.'"');
  }
  else if ($action == "reserve")
  {
    $aantal = Reservering::count_reservering_per_dag($dag, $week, $jaar, $tijd);

    if ($aantal < 3)
    {
      $query = mysql_query('SELECT MAX(counter) FROM '.DB_RESERVERING.' WHERE les_ID="'.$les_id.'"');
      $row = mysql_fetch_assoc($query);
      
      $counter = $row['MAX(counter)'] + 1;

      mysql_query('INSERT INTO '.DB_RESERVERING.' (les_ID, user_ID, counter) VALUES ("'.$les_id.'", "'.$user_id.'", "'.$counter.'")');
    }
  }
  else if ($action == "reserve_afmelden")
    mysql_query('DELETE FROM '.DB_RESERVERING.' WHERE les_ID="'.$les_id.'" AND user_ID="'.$user_id.'"');

  $url = BASE_URL;
  header("Location: $url/view/dag.php?d=$dag/$week/$jaar&t=$tijd");
?>